package org.jgs1904.apachepoidemo.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * BufferedImage image = ImageIO.read(new File("D:\\image\\OIP-A.jpg"));
 *
 * @author: 默苍璃
 * @date: 2023-10-12 14:24
 */

public class ExcelImageResizeExample {

    public static void main(String[] args) throws IOException {
        // 创建Excel工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 加载图片文件
        BufferedImage image = ImageIO.read(new File("D:\\image\\OIP-A.jpg"));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();

        // 创建绘图对象和锚点
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 3, 1, 0, 2);
        anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);

        // 插入图片并调整大小
        int pictureIndex = workbook.addPicture(byteArray, Workbook.PICTURE_TYPE_JPEG);
        Picture picture = drawing.createPicture(anchor, pictureIndex);
        picture.resize();

        // 获取图片的像素尺寸
        int pictureWidthInPixels = image.getWidth();
        int pictureHeightInPixels = image.getHeight();

        // 将图片的像素尺寸转换为单元格的宽度和高度
        double columnWidth = pixelsToPoints(pictureWidthInPixels);
        int rowHeight = Math.round((float) pointsToPixels(sheet.getDefaultRowHeightInPoints()));

        // 设置单元格的宽度和高度与图片一样
        sheet.setColumnWidth(anchor.getCol1(), (int) columnWidth);

        // 创建第二行并设置高度
        Row row = sheet.createRow(1);
        row.setHeight((short) rowHeight);

        // 保存Excel文件
        FileOutputStream fileOut = new FileOutputStream("D:\\image\\output.xlsx");
        workbook.write(fileOut);
        fileOut.close();

        System.out.println("Excel文件已生成。");
    }

    // 像素转换为点
    private static double pixelsToPoints(int pixels) {
        return Math.ceil((double) pixels * 0.75);
    }

    // 点转换为像素
    private static double pointsToPixels(double points) {
        return points / 0.75;
    }
}